package com.example.Sao.SqlLite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

/**
 * @ProjectName: scan
 * @Package: com.example.MyApplication.SqlLite
 * @ClassName: SQLiteDB
 * @Description: java类作用描述
 * @Author: 作者名
 * @CreateDate: 2020/4/21 20:38
 * @UpdateUser: 更新者：
 * @UpdateDate: 2020/4/21 20:38
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class SQLiteDB {

    /**  数据库名 */
    public static final String DB_NAME = "SQLite_Test";

    /** 数据库版本 */
    public static final int VERSION = 1;

    /** 数据库 */
    private static SQLiteDB sqliteDB;
    private RecordSQLiteOpenHelper dbHelper;
    private SQLiteDatabase db;

    private SQLiteDB(Context context) {
        /** 初始化数据库 */
        dbHelper = new RecordSQLiteOpenHelper(context);
        /** 获取db */
        db = dbHelper.getWritableDatabase();
    }

    /**
     * 获取SqliteDB实例
     * @param context
     */
    public synchronized static SQLiteDB getInstance(Context context) {
        if (sqliteDB == null) {
            sqliteDB = new SQLiteDB(context);
        }
        return sqliteDB;
    }
    /**
     * 插入数据
     */
   public void insertData(String table_name,String tempName) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }
    /**
     * 清空数据
     */
    public void deleteData(String table_name) {
        db = dbHelper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }
    /**
     * 检查数据库中是否已经有该条记录
     */
    public boolean hasData(String tempName) {
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**获取全部数据
     * @return
     */
    public ArrayList<String>getAll(String table_name){
      ArrayList<String>history = new ArrayList<>();
      Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from records",null);
      while (cursor.moveToNext()){
           history.add(cursor.getString(cursor.getColumnIndex("name")));
      }
      return history;
    }
}
